<template>
  <a-modal :title="openType ? '成片预览' : '素材预览'" :visible="visible" :footer="activeKey !== '4'? null : ''" wrapClassName="modal-name" :bodyStyle="{
    overflow: 'hidden',
    padding: 0,
    background: 'transparent',
  }" style="background: transparent;" @cancel="cancelClick" width="1200px" :closable="true"
    destroyOnClose>
    <a-row class="box">
      <a-col :flex="activeKey =='4' ? 0 : 1" class="left-box">
        <!-- 视频 -->
          <template v-if="activeKey !='4'">
            <video v-if="data.material_type == 'video'" class="img" controls>
              <source :src="data.material_url" type="video/mp4" />
              <source :src="data.material_url" type="video/quicktime" />
              <source :src="data.material_url" type="video/mpeg" />
              <source :src="data.material_url" type="video/3gpp" />
            </video>
            <a-row v-if="data.material_type == 'video'" style="padding-top: 15px" :gutter="[16,16]">
              <a-col>
                <a-button @click="intelligentSplitting">智能拆分</a-button>
              </a-col>
              <a-col>
                <a-button @click="extractText">提取文字</a-button>
              </a-col>
              <a-col v-if="!textList.length">
                <a-button @click="identifySubtitles">识别字幕</a-button>
              </a-col>
              <a-col v-for="item in appList" :key="item.key">
                <a-button @click="goTo(item)">
                  {{ item.name }}
                </a-button>
              </a-col>
            </a-row>
          </template>
        <!-- 音频 -->
        <div class="audio-box" v-if="data.material_type == 'audio'">
          <cu-icon type="icon-audio" class="auto-icon" />
          <audio :src="data.material_url" controls style="width: 500px" />
        </div>

        <!-- 图片 -->
        <a-spin :spinning="spinning" tip="加载中..." v-if="data.material_type == 'image'">
          <div class="img-box">
            <img :src="data.material_url" class="img" @load="imageLoaded" />
            <div class="mask"><eye-outlined @click="priewImgHandle(data.material_url)" class="icon_eye"
                style="color: #fff;font-size: 30px;" /></div>
          </div>
        </a-spin>
      </a-col>
      <a-col class="right-box" :style="{flex: activeKey =='4' ? 1 : ''}">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="基本信息" />
          <a-tab-pane key="2" tab="属性" />
          <a-tab-pane key="3" tab="发布信息" v-if="openType" />
          <a-tab-pane key="4" tab="素材字幕" v-if="activeKey == '4' || textList.length > 0" />
        </a-tabs>
        <a-form :label-col="{ span: 8 }">
          <template v-if="activeKey == '1'">
            <a-form-item :colon="false" label="标题">
              {{ data.material_name }}
            </a-form-item>
            <a-form-item :colon="false" label="扩展名">
              {{ data.material_extension }}
            </a-form-item>
            <a-form-item :colon="false" label="素材时长" v-if="data.material_type == 'audio'">
              {{ data?.material_duration_text || "--" }}
            </a-form-item>
            <a-form-item :colon="false" label="添加时间">
              {{ data.created_at }}
            </a-form-item>
            <a-form-item :colon="false" label="更新时间">
              {{ data.updated_at }}
            </a-form-item>
            <a-form-item :colon="false" label="引用次数">
              {{ data.usage_count }} 次
            </a-form-item>
            <a-form-item :colon="false" label="标签">
              <a-tag style="margin-bottom: 5px; cursor: pointer" @click="addTag">+ 添加标签</a-tag>
              <a-tag v-for="(item, index) in data.bind_tags" :key="index" style="margin-bottom: 5px">
                <a-tooltip zIndex="9999" v-if="item.tag?.name?.length > 10" :title="item.tag?.name">
                  <span style="cursor: pointer;">
                    {{ `${item.tag?.name.slice(0, 10)}...` }}
                  </span>
                </a-tooltip>
                <span v-else>
                  {{ item.tag?.name }}
                </span>
              </a-tag>
            </a-form-item>

            <a-form-item v-if="data.folder?.merchant && data.folder?.merchant?.name" :colon="false" label="所在项目">
              {{ data.folder?.merchant?.name }}
            </a-form-item>

            <a-form-item v-if="data.folder?.folder_name" :colon="false" label="所在文件夹">
              {{ data.folder?.folder_name }}
            </a-form-item>

            <a-form-item :colon="false">
              <template #label>
                {{
                  data.material_type == "audio"
                    ? "音频"
                    : data.material_type == "video"
                      ? "视频"
                      : "图片"
                }}
              </template>
              <!-- 视频 -->
              <video v-if="data.material_type == 'video'" :src="data.material_url"
                style="width: 100%; height: 100px; border-radius: 10px" />
              <!-- 图片 -->
              <img v-if="data.material_type == 'image'" :src="data.material_url" class="cover-box" />
              <div v-if="data.material_type == 'audio'" class="audio-cover">
                <cu-icon type="icon-audio" style="font-size: 30px" />
              </div>

              <div>
                <a style="color: blue" @click="downLoad">下载
                  {{
                    data.material_type == "audio"
                      ? "音频"
                      : data.material_type == "video"
                        ? "视频"
                        : "封面"
                  }}
                </a>
              </div>
            </a-form-item>
          </template>
          <template v-if="activeKey == '2'">
            <a-form-item :colon="false" label="媒资类型">
              <div v-if="data.material_type == 'image'">图片</div>
              <div v-if="data.material_type == 'video'">视频</div>
              <div v-if="data.material_type == 'audio'">音频</div>
            </a-form-item>
            <a-form-item :colon="false" label="文件大小">
              {{ data.material_size_text || "--" }}
            </a-form-item>
            <a-form-item :colon="false" label="文件格式">
              {{ data.material_extension || "--" }}
            </a-form-item>
            <a-form-item :colon="false" label="文件宽高" v-if="data.material_type != 'audio'">
              <span v-if="data.width && data.height">
                {{ data.width + " × " + data.height }}
              </span>
              <span v-else>--</span>
            </a-form-item>
            <a-form-item :colon="false" label="分辨率" v-if="data.material_type != 'audio'">
              {{ data?.material_exif?.display_aspect_ratio || "--" }}
            </a-form-item>
          </template>
          <template v-if="activeKey == '3'">
            <a-spin :spinning="publishInfoSping" v-if="publishList.length">
              <div class="publish_list">
                <div class="publish_item" v-for="ele in publishList">
                  <div class="platform_logo">
                    <img :src="ele.icon" alt="" />
                  </div>
                  <div class="platform_info">
                    <div style="line-height: 1" class="account_name">
                      发布账号：{{ ele.account_name }}
                    </div>
                    <div style="line-height: 1" class="user_name">
                      发布人：{{ ele.user_name }}
                    </div>
                    <div style="line-height: 1" class="publish_time">
                      {{ ele.release_time }}
                    </div>
                  </div>
                </div>
              </div>
            </a-spin>
            <a-empty v-else :image="simpleImage"></a-empty>
          </template>
          <!-- 素材字幕 -->
          <template v-if="activeKey == '4'">

              <IdentifySubtitles type="materia" 
                :detailItem="detailItem" :textList="textList" :fontList="fontList" 
                :flowerArr="flowerArr" :presetStylesList="presetStylesList" @stepChange="stepChange" :current="current" 
                :nextNum="nextNum" :successData="successData" @successChange="successChange"
                  @nextDisabledChange="nextDisabledChange"/>

              <a-row class="foot-button" :gutter="[16,16]">
                <a-col>
                  <a-button type="primary" @click="handleOk" :loading="submitLoading">
                    {{ nextNum === 0? '仅保存(字幕)' : '生成字幕视频'}}
                  </a-button>
                </a-col>
                <a-col>
                  <a-button  @click="stateNext" :disabled="nextDisabled"> 
                    {{ nextNum === 0? '下一步(生成字幕)' : '上一步'}}</a-button>
                </a-col>
              </a-row>
          </template>
        </a-form>
      </a-col>
    </a-row>
    
    <loadingMask ref="loadingMaskRef" :text="loadingText" :zIndex="1001" :loading="loading" />
  </a-modal>

    <!-- 充值弹窗 -->
    <vipModal :visible="vipVisible" @close="vipVisible = false" />
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  createVNode,
  computed,
  ref,
  nextTick,
  watch,
} from "vue";
import request from "@/common/utils/request";
import { Empty,message } from "ant-design-vue";
import { type } from "jquery";
import { EyeOutlined } from '@ant-design/icons-vue'
import { useRouter } from "vue-router";
import store from "@/store/index.js";

import IdentifySubtitles from "@/views/shotstack/components/IdentifySubtitles/index.vue"
import loadingMask from '@/components/loadingMask/index.vue'
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'

import utils from "@/common/utils/utils.js";


export default defineComponent({
  name: "FileDetailModal",
  components: {
    EyeOutlined,
    IdentifySubtitles,
    loadingMask,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
    index: {
      type: [Number, String],
      default: 0,
    },
    isPublish: {
      type: Boolean,
      default: false,
    },
    openType: {
      type: String,
      default: "",
    },
  },
  setup(props, { emit }) {
    const loadingMaskRef = ref()
    const state = reactive({
      count: 0,
      activeKey: "1",
      spinning: true,
      publishList: [],
      publishInfoSping: false,

      // 系统花字列表
      flowerArr: [],
      // 阿里花字列表
      flowerAliArr: [],
      // 字体列表
      fontList:[],
      // 折叠样式
      isFlod: false,
      flower_type: 'effectColor',
      // 选择字体开关
      selectFontPop: false,
      // 编辑的 item
      detailItem: null,
      // 头部进度条
      current: 0,

      // 字幕编辑列表
      textList: [],
      // 字幕列表 基础数据, 用于重置时使用
      baseTextList: [],
      newTextList: [],

      // 提交 需要的任务id
      job_id: '',
      presetStylesList:[],

      loading: false,
      loadingText:'字幕获取中...',
      nextDisabled:false,
      nextNum:0,
      successData:false,
      submitLoading:false,
      saveVisible: false,

      // 充值弹窗开关
      vipVisible:false,
      appList:[
        {
          name:'视频去除音频', 
          key:'spqcyp',
          routeName:'VideoRemoveAudioIndex',
        },
        {
          name:'视频裁剪',
          key:'sqcj',
          routeName:'VideoCroppingIndex',
        },
        {
          name:'视频擦除字幕',
          key:'sqcczm',
          routeName:'VideoRemoveSubtitlesIndex', 
        },
        {
          name:'视频擦除标志',
          key:'sqccbz',
          routeName:'VideoRemoveSignIndex', 
        },
        {
          name:'视频翻译',
          key:'spfy',
          routeName:'VideoTranslateIndex', 
        }
      ],
    });

    const router = useRouter();

    const downLoad = () => {
      saveAs(props.data.material_url, props.data.name);
    };

    const cancelClick = () => {
      emit("onClose");
    };

    const addTag = () => {
      emit("addTagChange", props.data, props.index);
    };

    const imageLoaded = () => {
      state.spinning = false;
    };

    const intelligentSplitting=()=>{
      store.dispatch('setSceneCreationSubtileTitles',props.data)
      setTimeout(() => {
        router.push({name:'AddVideoIntelligentSplit'})
      }, 200);
    }

    const extractText=()=>{
      store.dispatch('setExtractTextData',props.data)
      setTimeout(() => {
        router.push({name:'AddVideoToText'})
      }, 200);
    }


    // 步骤条 下一步的禁用逻辑
  const nextDisabledChange=(val)=>{
    state.textList = val
    state.newTextList = JSON.parse(JSON.stringify(val))
    state.nextDisabled = val.length ? false : true
  }

  const stateNext=()=>{
    getFontFlower()
    if(state.nextNum==1){
      state.nextNum = 0
      return
    }
    state.nextNum = 1
  }
  

  const stepChange=(num)=>{
    state.nextNum = num
    getFontFlower()
  }

  // 提交
const handleOk = async () => {  
  // 通知子组件是否提交数据
  state.successData = !state.successData
}

// 提交数据
const successChange= async (data) => {  

    if(!data.job_id){
      data.job_id = state.job_id
    }
    setTimeout(()=>{
      // 仅生成字幕
      if(state.nextNum == 0){
        // 判断有没有生成字幕
        if(!data.output.length){
          message.warning('请先生成字幕信息后在提交')
          return
        }else{
            // 判断有没有改动
          if(!compareContent(state.newTextList, data.output )){
              postUpMultimediaCaptions(data).then(()=>{
                message.success('保存成功')
                cancelClick()
              })
          }else{
            cancelClick()
          }
        }
      } else {
      // 生成字幕视频
        pointConsumption().then(async (res)=>{
          submitData(data)
        })
      }
    },20)
}

// 仅保存字幕的接口
const postUpMultimediaCaptions = (data) => {
  state.submitLoading = true
  return new Promise(async(resolve, reject) => {
    request.post('/work_ai','/user/shotstack/media/upMultimediaCaptions',data).then((res)=>{
      resolve()
      state.submitLoading = false
    }).catch(()=>{
      reject()
      state.submitLoading = false
    })
  })
    
}

function compareContent(arr1, arr2) {
    if (arr1.length!== arr2.length) {
        return false;
    }
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i].content!== arr2[i].content) {
            return false;
        }
    }
    return true;
}


const submitData= async (data)=>{
    state.submitLoading = true
    let params ={}
    params ={...data}
      // 匹配大部分emoji的正则表达式（持续更新版本）
      const emojiRegex = /[\u{1F300}-\u{1F5FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{FE00}-\u{FE0F}]/gu;
      if(!params.job_id){
        params.job_id = state.job_id
      }
      if(!params?.font_config.font_family){
        params.font_config = {...formState}
      }
      setTimeout(async ()=>{
        if(Object.keys(params).length){
          try {
              console.log(params, '即将提交的数据');
              const uniqueIdRes = await request.get("/work_ai", "/user/platform/uniqueId")
              params.unique_id = uniqueIdRes.uniqueId
              if(!params.material_type){
                params.material_type = props.data.material_type
              }
              if(!params.merchant_folder_statck_id){
                params.merchant_folder_statck_id = props.data.merchant_folder_statck_id
              }
              const res = await request.post("/work_ai","/user/shotstack/media/captionsTts/submitMedia",params);    
              console.log(res,'生成字幕视频提交结果');
              if(res?.code && res?.code != 1000) return message.error(res?.msg || '提交失败!')
              message.success('提交成功!')
              // 打开 数字人生成字幕 tab
              emit('onSubmitMedia')
          } finally {
            state.submitLoading = false
          }
        }
      },10)

      

    
}

  // 点数信息
  const countData = ref(null)
  // 点数消耗查询
  const pointConsumption = (number = 1) => {
    return new Promise(async(resolve, reject) => {
      let url ="/user/shotstack/media/point/get"
      const res = await request.get(
        "/work_ai",
        url,
        { number , type: 'business_module_multimedia_video_point',key: 'clip_video_point' }
      );
      countData.value = res
      if (countData.value?.usable != 1) {
          // 打开充值弹窗
        state.vipVisible = true
        reject('点数不足')
        return
      }
      // 获取消耗提示词内容
      const content = utils.useText(countData.value)

      try {      
        // 打开积分消耗提示
        await utils.kd({
          content,
          res:countData.value
        })
        resolve('点数足够,同意消耗')
      } catch (error) {
        reject('不同意消耗')
      }
    })
  }

    // 识别字幕
    const identifySubtitles=(isTab=true)=>{
      console.log(props.data,'data');
      state.detailItem = {
        id: props.data.id,
        video_url: props.data.material_url,
        folderName: props.data.folderName,
      }
      if(props.data?.folder_name){
        state.detailItem.folderName = props.data?.folder_name
      }
      // 查询是否已经有了字幕信息
      haveVideoText()
      getFontFlower()
      if(isTab){
        state.activeKey = "4";
      }
    }

    const getFontFlower=()=>{
      // 花字列表
      getFlowerListData()
      // 字体列表
      getFontList()
    }
// 查询是否已经有了字幕信息
const haveVideoText = async () => {
  state.loading = true

  try {
    const res = await request.get(
    "/work_ai",
    "/user/shotstack/media/mediaCaptions",
    {
      multimedia_id: state.detailItem.id,
    }
  );
    console.log(res, '是否有字幕');
    const textList = res.result?.ai_result?.SubtitleTracks || []
    
    if(Array.isArray(textList) && textList.length) {
      setTimeout(()=>{
        state.newTextList =JSON.parse(JSON.stringify(textList))  
        state.textList = textList
        state.nextDisabled = false
        state.baseTextList = JSON.parse(JSON.stringify(state.textList))
        state.job_id = res.result?.job_id
      },10)
    }else{
      state.nextDisabled = true
    }
  } catch (error) {
    
  } finally {
    state.loading = false 
  }
}



// 获取系统花字列表
const getFlowerListData = async () => {
      const presetStyles = await request.get(
        "/work_ai",
        "/user/shotstack/material/presetStyles/list"
    );
    state.presetStylesList = presetStyles
    state.flowerArr = presetStyles?.result;
    state.flowerAliArr = presetStyles?.resultEffect;
}

// 获取字体列表
const getBaseFormData = () => {
  return {
    font_family: '',
    font_name: '',
    font_url: '',
    font_size: 45,
    font_path:'',
    // 字体颜色
    color: '#000000',
    bg_color: '',
    bold: 0,
    italic:0,
    alignment: "center",

    // 花字id
    flower_id: '',
    flower_type:'effectColor',// system 是我们自己的花字， 'effectColor' 表示是用的阿里云的
}
}

const formState = reactive(getBaseFormData())
const getFontData = ref({})
const getFontList = async () => {
  const res = await  request.get("/work_ai", "/user/shotstack/material/fonts/list")
  res.result.map((item) => {
      item.label = item.name;
      item.value = item.material_url;
  });
  state.fontList = res.result;

  const find = state.fontList.find((item) => item.id_default == 1);

  let data = {
      font_name: find.name,
      font_path: find.material_path,
      font_style: find.font_style,
      font_family: find.font_family,
      font_url: find.material_url,
  }
  Object.assign(formState, data)
}




    watch(
      () => props.visible,
      (val) => {
        if (val) {
          state.activeKey = "1";
          state.publishList = [];
          getPublishDetail();
          identifySubtitles(false)
        } else {
          state.textList = []
          state.nextNum = 0
        }
      }
    );
    watch(
      () => props.isPublish,
      (val) => {
        if (val) {
          state.activeKey = "3";
        }
      }
    );
    // 获取发布信息详情
    const getPublishDetail = () => {
      state.publishInfoSping = true;
      request
        .get("/work_ai", "/user/shotstack/media/relation", {
          multimedia_id: props.data.id,
        })
        .then((res) => {
          state.publishInfoSping = false;
          if (res) {
            state.publishList = res.result;
          }
        })
        .catch((err) => {
          state.publishInfoSping = false;
        })
        .finally(() => {
          state.publishInfoSping = false;
        });
    };
    const priewImgHandle = (url) => {
      window.open(url)
    }
    const goTo = (item) => {
      store.dispatch('setApplicationMaterialData',props.data)
      setTimeout(() => {
        router.push({name:item.routeName})
      }, 200);
    }
    return {
      ...toRefs(state),
      cancelClick,
      downLoad,
      addTag,
      imageLoaded,
      getPublishDetail,
      priewImgHandle,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      intelligentSplitting,
      extractText,
      identifySubtitles,
      loadingMaskRef,
      nextDisabledChange,
      stateNext,
      stepChange,
      successChange,
      handleOk,
      goTo,
 
    };
  },
});
</script>

<style lang="less">
.modal-name {
  .ss-modal-content {
    box-shadow: none;
    background: transparent;
  }
}
</style>

<style lang="less" scoped>
.box {
  min-width: 1110px;

  .left-box {
    height: 600px;
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding-bottom: 15px;

    // border-top-left-radius: 10px;
    // border-bottom-left-radius: 10px;
    video {
      height: calc(100% - 38px) !important;
      border: 1px solid #eae5e5;
    }

    .img {
      width: 825px;
      height: 500px;
      object-fit: contain;
    }

    .img-box {
      position: relative;
      width: 825px;
      height: 500px;

      .mask {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        transform: translate(-50%, -50%);
        background-color: rgba(0, 0, 0, 0.2);
        visibility: hidden;
        display: flex;
        justify-content: center;
        align-items: center;

        .icon_eye {
          cursor: pointer;

          &:hover {
            color: var(--ss-primary-color) !important;
          }
        }
      }

      &:hover .mask {
        visibility: visible;
      }

    }

    .audio-box {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      background: rgba(0, 0, 0, 0.2);

      .auto-icon {
        font-size: 60px;
        margin-bottom: 100px;
      }
    }
  }

  .right-box {
    height: 600px;
    width: 270px;
    background: #fff;
    padding: 10px;
    padding-top: 0;
    overflow-y: auto;
    // border-top-right-radius: 10px;
    // border-bottom-right-radius: 10px;
    padding-right: 7px;

    &::-webkit-scrollbar {
      width: 9px;
      margin-right: 2px;
      display: none;
    }

    :deep(.ss-form-item) {
      margin-bottom: 10px;
    }

    :deep(.ss-form-horizontal .ss-form-item-label) {
      padding-right: 30px !important;
      text-align: left;
    }

    :deep(.ss-form-item-label > label) {
      color: #78797b;
    }

    .cover-box {
      width: 165px;
      height: 100px;
      object-fit: contain;
      margin-bottom: 5px;
      border-radius: 5px;
    }

    .audio-cover {
      width: 100%;
      height: 60px;
      background: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 5px;
    }

    // 发布信息列表
    .publish_list {
      width: 100%;
      max-height: 440px;
      overflow-y: auto;
      padding-right: 10px;

      &::-webkit-scrollbar {
        width: 5px;
        /* 滚动条的宽度 */
        height: 10px;
        /* 滚动条的高度，垂直滚动条可能用得上 */
      }

      &::-webkit-scrollbar-thumb {
        background: #888;
        /* 滑块的背景颜色 */
        border-radius: 10px;
        /* 滑块的圆角 */
      }

      .publish_item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border: 1px solid #f0f0f0;
        padding: 5px 10px;
        margin-top: 10px;
        width: 100%;
        height: 80px;
        box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.05);
        border-radius: 5px;

        &:nth-child(1) {
          margin-top: 0;
        }

        .platform_logo {
          margin-right: 10px;

          img {
            width: 50px;
            height: 50px;
            object-fit: cover;
          }
        }

        .platform_info {
          height: 56px;
          font-size: 13px;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .publish_time,
          .account_name,
          .user_name {
            max-width: 160px;
            white-space: nowrap;
            /* 防止文本换行 */
            overflow: hidden;
            /* 隐藏溢出内容 */
            text-overflow: ellipsis;
            /* 显示省略号 */
          }
        }
      }
    }
    .foot-button{
      position: relative;
      bottom: -20px;
      right: -910px;
    }
  }
}


</style>
